package com.yh.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yh.model.Permission;
import com.yh.service.PermissionService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.security.RolesAllowed;
import java.util.List;

@Controller
@RequestMapping("permission")
public class PermissionController {
    @Autowired
    PermissionService permissionService;


    @RolesAllowed("ADMIN")
    @RequestMapping("findAll")
    public String findAll(@RequestParam(name = "page", defaultValue = "1") Integer page,
                          @RequestParam(name = "size", defaultValue = "5") Integer size,
                          Model model) {
        PageHelper.startPage(page, size);
        List<Permission> permissionList = permissionService.findAll();
        PageInfo<Permission> pageInfo = new PageInfo<>(permissionList);

        model.addAttribute("pageInfo",pageInfo);
        return "permission-list";
    }


    @GetMapping("findById")
    public String findById(@RequestParam("id") String id, Model model) {
        Permission permission = permissionService.findById(id);
        model.addAttribute("permission",permission);
        return "permission-show";
    }

    @DeleteMapping("deletePermission")
    public String deletePermission(@RequestParam("id") String id) {
        permissionService.deleteById(id);
        return "redirect:findAll";
    }


    @RequestMapping("save")
    public String save(Permission permission) {
        permissionService.save(permission);
        return "redirect:findAll";
    }
}
